package com.gexiaobao.pigeon.ui.pigeoncatcher

import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.os.Bundle
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseActivity
import com.gexiaobao.pigeon.app.eventViewModel
import com.gexiaobao.pigeon.app.ext.countDownCoroutines
import com.gexiaobao.pigeon.app.model.param.GetVerCodeParams
import com.gexiaobao.pigeon.app.model.param.ShedSignParam
import com.gexiaobao.pigeon.app.model.param.UserSignParam
import com.gexiaobao.pigeon.app.util.ImageLoaderManager
import com.gexiaobao.pigeon.app.util.ImgUtils
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.databinding.ActivityDovetailSignBinding
import com.gexiaobao.pigeon.viewmodel.PigeonCatcherViewModel
import com.wynsbin.vciv.VerificationCodeInputView
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.startActivityForResult
import java.io.File


/**
 * @Author      : hxw
 * @Date        : 2024/6/28 14:33
 * @Describe    : 签字确认（滴滴接鸽）
 */
class ActivityDovetailSign : BaseActivity<PigeonCatcherViewModel, ActivityDovetailSignBinding>(), VerificationCodeInputView.OnInputListener {

    private var verificationCode = ""
    private var phone = ""
    private var mShenPhone = ""
    private var userFile: File? = null
    private var transporterFile: File? = null
    private var mOrderId = ""
    private var mStatus = 0

    @SuppressLint("SetTextI18n")
    override fun initView(savedInstanceState: Bundle?) {
        StatusBarUtil.setTranslucentForImageView(this, 0, null)
        mDatabind.includeBar.tvTitle.text = "签字确认"

        mStatus = intent.getIntExtra("status", 0)
        mOrderId = intent.getStringExtra("orderId").toString()
        phone = intent.getStringExtra("phone").toString()
        mShenPhone = intent.getStringExtra("shedPhone").toString()
        if (mStatus == 3) {
            if (phone.isNotEmpty() && phone.length >= 11) {
                val result1 = phone.substring(0, 3)
                val result2 = phone.substring(7, phone.length)
                mDatabind.tvDovetailSignPhone.text = "$result1****$result2"
            }
        } else {
            if (mShenPhone.isNotEmpty() && mShenPhone.length >= 11) {
                val result1 = mShenPhone.substring(0, 3)
                val result2 = mShenPhone.substring(7, mShenPhone.length)
                mDatabind.tvDovetailSignPhone.text = "$result1****$result2"
            }
        }
        mDatabind.tvUserSign.text = if (mStatus == 3) "用户签:" else "公棚签:"
        mDatabind.llTransporterSign.isVisible = mStatus == 3
        mDatabind.verificationCode.setOnInputListener(this)
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(
            mDatabind.includeBar.ivBack,
            mDatabind.tvSendVerificationCode,
            mDatabind.btnSubmitSign,
            mDatabind.ivUserSign,
            mDatabind.ivTransporterSign
        ) {
            when (it) {
                mDatabind.btnSubmitSign -> {
                    if (mStatus == 3) {
                        submitSign()
                    } else {
                        submitSignShed()
                    }
                }

                mDatabind.ivUserSign -> {
                    startSign("user")
                }

                mDatabind.ivTransporterSign -> {
                    startSign("transporter")
                }

                mDatabind.tvSendVerificationCode -> {
                    sendCode()
                }

                mDatabind.includeBar.ivBack -> {
                    finish()
                }
            }
        }
    }

    private fun submitSignShed() {
        when {
            verificationCode.isEmpty() && verificationCode.length != 6 -> RxToast.warning("请输入验证码进行身份验证")
            userFile == null -> RxToast.warning("请公棚签名")
            else -> {
                val param = ShedSignParam(
                    signOrg = userFile,
                    id = mOrderId.toInt(),
                    code = verificationCode,
                    mobile = mShenPhone
                )
                showLoading(getString(R.string.loading))
                mViewModel.completeOrderDidi(param)
            }
        }
    }

    private fun startSign(type: String) {
        startActivityForResult(ActivitySign::class) {
            if (it != null) {
                val path = it.getStringExtra("filePath").toString()
                val originalBitmap = ImgUtils.getSmallBitmap(path)
                val scaledBitmap = Bitmap.createScaledBitmap(originalBitmap, 400, 800, true)
                if (type == "user") {
                    userFile = File(path)
                    mDatabind.ivUserSign.setImageBitmap(scaledBitmap)
                } else {
                    mDatabind.ivTransporterSign.setImageBitmap(scaledBitmap)
                    transporterFile = File(path)
                }
            }
        }
    }

    private fun submitSign() {
        when {
            verificationCode.isEmpty() && verificationCode.length != 6 -> RxToast.warning("请输入验证码进行身份验证")
            userFile == null -> RxToast.warning("请用户签名")
            transporterFile == null -> RxToast.warning("请司机签名")
            else -> {
                val param = UserSignParam(
                    signUser = userFile,
                    signTransporter = transporterFile,
                    id = mOrderId.toInt(),
                    code = verificationCode,
                    mobile = phone
                )
                showLoading(getString(R.string.loading))
                mViewModel.receivePigeonWithOrderDidi(param)
            }
        }
    }

    override fun createObserver() {
        super.createObserver()
        /** 依据接鸽清单收鸽（接鸽员角色）（公棚签字确认）（订单状态变更） */
        mViewModel.shedSignResult.observe(this) {
            if (it.isSuccess) {
                eventViewModel.toRefreshDataStr.value = "ActivityDovetailSign"
                RxToast.showToast("验证成功")
                finish()
            } else {
                RxToast.warning(it.errorMsg)
            }
        }
        /** 接鸽（接鸽员角色）（鸽友签字确认）（订单状态变更） */
        mViewModel.userAndTranSignResult.observe(this) {
            if (it.isSuccess) {
                eventViewModel.toRefreshDataStr.value = "ActivityDovetailSign"
                RxToast.showToast("验证成功")
                finish()
            } else {
                RxToast.warning(it.errorMsg)
            }
        }
        /** 发送验证码 */
        mViewModel.verCodeResult.observe(this) {
            if (it.isSuccess) {
                RxToast.showToast("发送成功")
            } else {
                RxToast.warning(it.errorMsg)
            }
        }
    }

    @SuppressLint("SetTextI18n")
    private fun sendCode() {
        //开启倒计时60s
        job = countDownCoroutines(60, {
            mDatabind.tvSendVerificationCode.text = ("${it}s后重新发送")
        }, {
            mDatabind.tvSendVerificationCode.text = "获取验证码"
        }, lifecycleScope)
        val body = if (mStatus == 3) {
            GetVerCodeParams(phone, 2)
        } else {
            GetVerCodeParams(mShenPhone, 2)
        }
        mViewModel.getVerCode(body)
    }

    override fun onComplete(code: String?) {
        verificationCode = code.toString()
    }

    override fun onInput() {

    }

}